import React, { useRef } from 'react'
import * as echarts from 'echarts'
import { useEffect, useState } from 'react'
import { GET_STUDENT } from '../../api/student'
type EChartsOption = echarts.EChartsOption;
// 定义 EChartsOption 类型  
function Zuo2() {
  const [data,setData] = useState({})
  const [serdata,setserData] = useState({})
  useEffect(() => {
  GET_STUDENT().then((res: any) => {
    const legendData = res.data.data.result[0].legend.data;
    const seriesData = res.data.data.result[0].series; // 假设从API获取的数据中包含了系列数据

    const newOptions = {
      ...options,
      legend: {
        ...options.legend,
        data: legendData,
      },
      series: seriesData, // 更新系列数据
    };
    setOptions(newOptions); // 更新图表选项
  });
}, []);
  const [options, setOptions] = useState({
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: [data],
      icon: 'circle',
      textStyle: {
        color: "#fff"
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: 'Email',
        type: 'line',
        stack: 'Total',
        smooth: true,
        showSymbol: false,
        data: [120, 132, 101, 134, 90, 230, 210]
      },
      {
        name: 'Union Ads',
        type: 'line',
        stack: 'Total',
        smooth: true,
        showSymbol: false,
        data: [220, 182, 191, 234, 290, 330, 310]
      },
      {
        name: 'Video Ads',
        type: 'line',
        stack: 'Total',
        smooth: true,
        showSymbol: false,
        data: [150, 232, 201, 154, 190, 330, 410]
      },
      {
        name: 'Direct',
        type: 'line',
        stack: 'Total',
        smooth: true,
        showSymbol: false,
        data: [320, 332, 301, 334, 390, 330, 320]
      },
    ]
  });
  const chartRef = useRef(null);// 创建一个ref来存储DOM元素的引用 
    useEffect(() => {
        if (chartRef.current) { // 确保DOM元素已经被挂载
            var myChart = echarts.init(chartRef.current);// 使用current属性访问DOM元素
            myChart.setOption(options)// 设置图表选项  
            // 窗口大小自适应
            window.addEventListener('resize', () => {
                myChart.resize()
            })
            // 清除监听器  可写可不写
            return () => {
                window.removeEventListener('resize',()=>myChart.resize());
                if(myChart){
                    myChart.dispose();
                }
            }
        }
    },[options])// 当options改变时,重新渲染图表

  return (
    <div ref={chartRef} style={{ width: '22vw', height: '35vh '}}></div>
  )
}
export default Zuo2